from datetime import datetime
from app import db


class MembershipOrder(db.Model):
    """会员订单模型"""
    __tablename__ = 'membership_orders'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, comment='用户ID')
    matchmaker_id = db.Column(db.Integer, db.ForeignKey('matchmakers.id', ondelete='SET NULL'), comment='推荐红娘ID')
    membership_type = db.Column(db.String(20), nullable=False, comment='会员类型：silver银卡,gold金卡,diamond钻石')
    duration = db.Column(db.Integer, nullable=False, comment='时长（月）')
    original_price = db.Column(db.Numeric(10, 2), nullable=False, comment='原价')
    actual_price = db.Column(db.Numeric(10, 2), nullable=False, comment='实付金额')
    discount_amount = db.Column(db.Numeric(10, 2), default=0, comment='优惠金额')
    commission_amount = db.Column(db.Numeric(10, 2), default=0, comment='佣金金额')
    commission_rate = db.Column(db.Numeric(5, 2), default=0, comment='佣金比例')
    payment_method = db.Column(db.String(50), comment='支付方式')
    payment_status = db.Column(db.Integer, default=1, comment='支付状态：1待支付2已支付3已退款4已取消')
    order_no = db.Column(db.String(50), unique=True, nullable=False, comment='订单号')
    payment_time = db.Column(db.DateTime, comment='支付时间')
    start_time = db.Column(db.DateTime, comment='会员开始时间')
    end_time = db.Column(db.DateTime, comment='会员结束时间')
    matchmaking_times = db.Column(db.Integer, default=0, comment='赠送牵线次数')
    used_matchmaking_times = db.Column(db.Integer, default=0, comment='已使用牵线次数')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 索引
    __table_args__ = (
        db.Index('idx_user_id', 'user_id'),
        db.Index('idx_matchmaker_id', 'matchmaker_id'),
        db.Index('idx_order_no', 'order_no'),
        db.Index('idx_payment_status', 'payment_status'),
    )

    def __repr__(self):
        return f'<MembershipOrder {self.order_no}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'matchmaker_id': self.matchmaker_id,
            'membership_type': self.membership_type,
            'membership_type_text': self._get_membership_type_text(),
            'duration': self.duration,
            'original_price': float(self.original_price) if self.original_price else 0,
            'actual_price': float(self.actual_price) if self.actual_price else 0,
            'discount_amount': float(self.discount_amount) if self.discount_amount else 0,
            'commission_amount': float(self.commission_amount) if self.commission_amount else 0,
            'commission_rate': float(self.commission_rate) if self.commission_rate else 0,
            'payment_method': self.payment_method,
            'payment_status': self.payment_status,
            'payment_status_text': self._get_payment_status_text(),
            'order_no': self.order_no,
            'payment_time': self.payment_time.strftime('%Y-%m-%d %H:%M:%S') if self.payment_time else None,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S') if self.start_time else None,
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'matchmaking_times': self.matchmaking_times,
            'used_matchmaking_times': self.used_matchmaking_times,
            'remaining_matchmaking_times': self.matchmaking_times - self.used_matchmaking_times if self.matchmaking_times and self.used_matchmaking_times else 0,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
    
    def _get_membership_type_text(self):
        """获取会员类型文本"""
        type_map = {
            'silver': '银卡会员',
            'gold': '金卡会员',
            'diamond': '钻石会员'
        }
        return type_map.get(self.membership_type, '未知')
    
    def _get_payment_status_text(self):
        """获取支付状态文本"""
        status_map = {
            1: '待支付',
            2: '已支付',
            3: '已退款',
            4: '已取消'
        }
        return status_map.get(self.payment_status, '未知') 